import struct, socket, time, threading
# 负责与服务端通信
class Client:
    def __init__(self):
        address = ('localhost', 9999)
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        
        self.client.connect(address)
        self.stateHeartbeat = True
        threadHeartbeat = threading.Thread(target=self.heartbeat)
        threadHeartbeat.setDaemon(True)
        threadHeartbeat.start()

    def __del__(self):
        self.client.close() 

    # 发送心跳包
    def heartbeat(self):
        try:
            while self.stateHeartbeat: # 因为心跳所以心跳，哈哈哈哈
                time.sleep(0.05)
                self.client.send(struct.pack('=I', 0))
        except ConnectionError:
            self.stateHeartbeat = False

    # 发送消息
    def send(self, content):
        try:
            self.client.send(struct.pack('=i', len(content)) + content)
        except ConnectionError:
            self.stateHeartbeat = False

    # 接收消息
    def recv(self):
        if not self.stateHeartbeat:
            return False
        try:
            lenData = struct.unpack('=i', self.client.recv(struct.calcsize('=I')))
            data = self.client.recv(lenData[0])
            self.client.send(struct.pack('=i', -1)) # 收到后需要回信才可以接收下一条内容
            return data
        except (ConnectionError, struct.error) as e:
            print(e)
            self.stateHeartbeat = False
            return False
        else:
            return None